import requests


def load_page(url):
    # 根据url发送请求，获取服务器相应

    header = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.86'
    }
    response = requests.get(url, headers=header)

    return response.text


def save_file(html, filename):
    # 将抓取的网页数据写入文件
    # html：服务器相应内容

    print("正在保存" + filename)
    with open(filename, 'w', encoding='utf-8') as file:
        file.write(html)


def heima_forum(begin_page, end_page):

    for page in range(begin_page, end_page+1):
        url = f'http://bbs.itheima.com/forum-425-{page}.html'   # 组合完整url
        filename = "第" + str(page) + "页.html"                 # 设置文件名称

        html = load_page(url)               # 抓取网页数据
        save_file(html, filename)           # 保存网页数据


if __name__ == "__main__":
    begin_page = int(input("请输入起始页码："))
    end_page = int(input("请输入结束页码："))
    heima_forum(begin_page, end_page)